import typing as T
from pydantic import BaseModel, Field
from starlette.requests import Request
import re


class InterceptEntity(BaseModel):
    method: T.Literal["GET", "POST", "PUT", "DELETE"] = Field(description="请求方法")
    endpoint: T.Callable = Field(description="路由函数")
    pattern: str = Field(description="路由正则表达式")

    def verify(self, method: str, path: str) -> bool:
        if self.method != method:
            return False
        if not re.fullmatch(self.pattern, path):
            return False
        return True


class ChatHistoryMap:
    def __init__(self):
        self.entities: T.List[InterceptEntity] = []

    def __contains__(self, key: Request):
        if not isinstance(key, Request):
            return False

        for entity in self.entities:
            if entity.verify(key.method, f"{key.url.path}"):
                return True
        return False

    def add(self, method: str, path: str, endpoint: T.Callable):
        pattern = re.sub(r"\{(\w+)\}", r"([^/]+)", path)
        pattern = f"^{pattern}$"
        self.entities.append(
            InterceptEntity(method=method, endpoint=endpoint, pattern=pattern)
        )
        return self


chatHistoryMap: ChatHistoryMap = ChatHistoryMap()
